package com.jushu.storbox.service;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Set;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.manager.DownloadTaskManager;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.image.ImageUtils;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;

public class LocalFileService extends AbstractLocalService implements ILocalFileService {

	@Override
	public long insertFile(FileInfoResponseV2 fileInfo) {
		return DAOFactory.instance(this.getContext()).getFileDao().insertFile(fileInfo);
	}

	@Override
	public void updateFile(FileInfoResponseV2 fileInfoResponse) {
		DAOFactory.instance(this.getContext()).getFileDao().updateFile(fileInfoResponse, false, false);
	}
	
	@Override
	public void updateFile(FileInfoResponseV2 fileInfoResponse, boolean resetFileDownloadState, boolean syncIdentity) {
		DAOFactory.instance(this.getContext()).getFileDao().updateFile(fileInfoResponse, resetFileDownloadState, syncIdentity);
	}

	@Override
	public void updateFile(FileInfo fileInfo) {
		DAOFactory.instance(this.getContext()).getFileDao().update(fileInfo);
	}

	@Override
	public void inserOrUpdateFile(FileInfoResponseV2 fileInfo) {
		// TODO
	}

	@Override
	public List<FileInfo> getFileList(FileFolderInfo info) {
		return DAOFactory.instance(this.getContext()).getFileDao().getFileList(info);
	}
	
	@Override
	public List<FileInfo> getFileList(String ownerId, String resId) {
		return DAOFactory.instance(this.getContext()).getFileDao().getFileList(ownerId, resId);
	}
	
	public HashMap<String, FileInfo> getMappedFileList(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFileDao().getMappedFileDatas(ownerId, folderId);
	}
	
	@Override
	public List<FileInfo> getFileListPage(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFileDao().getFileListPage(ownerId, folderId, Constant.MYCLOUD_GET_FILE_LIST_STATE);
	}

	@Override
	public FileInfo getFileById(FileFolderInfo info) {
		return DAOFactory.instance(this.getContext()).getFileDao().getFile(info);
	}

	@Override
	public void deleteFile(FileFolderInfo fileFolderInfo) {
		FileInfo fileInfo = DAOFactory.instance(this.getContext()).getFileDao().getFile(fileFolderInfo);
		if(fileInfo == null){
			LogUtil.w("LocalFileService", " deleteFile,target is empty");
			return;
		}
		iFileManager mdmTools = FileManagerFactory.getFileManager(this.getContext());
		if(fileInfo != null && ImageUtils.isImageType(fileInfo.getName())){ 
			mdmTools.deleteFile(DirectoryUtil.genThumbnailFileFullName(this.getContext(),fileInfo.getOwnerBy(),  fileInfo.getId(), fileInfo.getName()));
		}
		if(null != fileInfo && fileInfo.isSync()){
			mdmTools.deleteFile(fileInfo.getLoctPath());
		}
		DAOFactory.instance(this.getContext()).getFileDao().delete(fileFolderInfo);
	}
	
	@Override
	public void deleteFileVirtual(FileFolderInfo info) {
		DAOFactory.instance(this.getContext()).getFileDao().delete(info);
	}

	@Override
	public FileFolderInfo renameFile(FileInfoResponseV2 fileInfoResponse, FileFolderInfo fileInformation) {
		FileFolderInfo infos = null;
		try {
			iFileManager mdmTools = FileManagerFactory.getFileManager(this.getContext());

			String newFilePath = DirectoryUtil.generateFileDownloadPath(context, fileInformation.getOwnerId(), fileInformation.getId(), fileInfoResponse.getName());
	        String oldFilePath = DirectoryUtil.generateFileDownloadPath(context, fileInformation.getOwnerId(), fileInformation.getId(), fileInformation.getName());
	        
			boolean isRenameSuccess = mdmTools.rename(oldFilePath, newFilePath);
			
			LogUtil.e("~~", "moveFile rename :"+isRenameSuccess);
			DAOFactory.instance(this.getContext()).getFileDao().rename(fileInfoResponse, fileInfoResponse.getName());
			
			infos = DAOFactory.instance(this.getContext()).getFileDao().getFile(fileInfoResponse);
			LogUtil.e("testff", "infos.getName:"+infos.getName());
			LogUtil.e("testff", "infos.getName[1]:"+fileInfoResponse.getName());
			LogUtil.e("testff", "infos.getModifyTime:"+PublicTools.longToString(infos.getModifiedAt()));
			LogUtil.e("testff", "infos.getModifyTime[1]:"+PublicTools.longToString(fileInfoResponse.getModifiedAt()));
			LogUtil.e("~~", "infos.getLoctPath():"+infos.getLoctPath());
		} catch (Exception e) {
		}
		
		return infos;
	}

	@Override
	public void moveFile(FileFolderInfo file, FileFolderInfo targetFolder) {
		DAOFactory.instance(this.getContext()).getFileDao().move(file, targetFolder);
		
		DAOFactory.instance(this.getContext()).getFolderDao().setChangedFolderId(targetFolder, "1");
		
	}

	/**
	 * @param folderId
	 * @param folderName
	 */
	public void syncFile(FileFolderInfo info, String fileName) {
		DAOFactory.instance(this.getContext()).getFileDao().updateSyncStatus(info,1);
	}

	/**
	 * @param folderId
	 * @param folderName
	 */
	public void cancelSyncFile(FileFolderInfo info, String fileName) {
		FileInfo fileInfo = DAOFactory.instance(this.getContext()).getFileDao().getFile(info);
		if (fileInfo == null) {
			return;
		}
		String parentFolderId = fileInfo.getParent();
		FolderInfo parent = DAOFactory.instance(this.getContext()).getFolderDao().getFolderById(info.getOwnerId(), parentFolderId);
		if (parent != null && parent.isSync()) {
			DAOFactory.instance(this.getContext()).getFolderDao().updateSyncStatuc(info.getOwnerId(), parentFolderId,0);
		}
		DAOFactory.instance(this.getContext()).getFileDao().updateSyncStatus(info, 0);
	}

	@Override
	public void updateLocalPath(FileFolderInfo info, String localPath) {
		DAOFactory.instance(this.getContext()).getFileDao().updateLocalPath(info, localPath);
	}

	@Override
	public void updateTransStatus(FileFolderInfo info,int status) {
		DAOFactory.instance(this.getContext()).getFileDao().updateTransStatus(info, status);
	}

	@Override
	public void updateSyncStatus(FileFolderInfo info, int syncStatus) {
		DAOFactory.instance(this.getContext()).getFileDao().updateSyncStatus(info, syncStatus);
	}

	@Override
	public void getCloudDriveCache(final Handler handler) {
		// TODO Auto-generated method stub
		final int MDMSIZE = 1;
		new Thread(new Runnable() {
			@Override
			public void run() {
				double total = 0;
				// TODO Auto-generated method stub
				try {
					iFileManager mdmTools = FileManagerFactory.getFileManager(LocalFileService.this.getContext());
					total = mdmTools.getCloudDriveSize();
					total += PublicTools.getCloudDriveRMSDocmentSize();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					total = 0;
				}
				String cloudDriveSize = FileHelper.formatFileSize(total);
				Message msg = new Message();
				msg.what = MDMSIZE;
				msg.obj = cloudDriveSize;
				handler.sendMessage(msg);
			}
		}).start();
	}
	
	@Override
	public void clearCloudDriveCache(final Handler handler) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			@Override
			public void run() {
				
				Set<DownloadTask> downloadTasks = DownloadTaskManager.getAllTaskes();
				if (downloadTasks != null && downloadTasks.size() > 0) {
					for (DownloadTask task : downloadTasks) {
						task.cancelDownloadTask();
					}
				}
				
				PublicTools.clearCloudDriveData(LocalFileService.this.getContext());
				if(handler != null){
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

//	@Override
//	public boolean operateWhenMobileIsRoot() {
////		return PublicTools.checkIsRootAndNotify(LocalFileService.this.getContext());
//	}

	@Override
	public List<FileFolderInfo> getFileFolderInfos(Context context,
			String ownerId, String folderID, String des, String orderby) {
		// TODO Auto-generated method stub
		List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
		try {
			List<FolderInfo> folderInfoList = DAOFactory
					.instance(context)
					.getFolderDao()
					.getFolderListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE,
							ownerId, folderID, des, orderby);
			fileFolderInfoList.addAll(folderInfoList);
			List<FileInfo> fileInfoList = DAOFactory
					.instance(context)
					.getFileDao()
					.getFileListPage(ownerId, folderID, Constant.MYCLOUD_GET_FILE_LIST_STATE,
							des, orderby);
			fileFolderInfoList.addAll(fileInfoList);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return fileFolderInfoList;
	}

	@Override
	public List<FileFolderInfo> searchInDB(String ownerId, String fileName,Context context) {
		List<FileFolderInfo> resource = new ArrayList<FileFolderInfo>();
		List<FileInfo> fileList = DAOFactory.instance(context).getFileDao().getSearchFileList(ownerId,fileName);
		List<FolderInfo> folderist =DAOFactory.instance(context).getFolderDao().getSearchFolderList(ownerId, fileName);
		resource.addAll(fileList);
		resource.addAll(folderist);
		return resource;
	}
}
